/******************************************************************************

                           TIMER SOURCE FILE

 *******************************************************************************/
/**********************************************************************
* � 2009 Microchip Technology Inc.
*
* FileName:        TimerFunctions.c
* Dependencies:    Header (.h) files if applicable, see below
* Processor:       PIC32
* Compiler:        MPLAB� C32 
*
* SOFTWARE LICENSE AGREEMENT:
* Microchip Technology Incorporated ("Microchip") retains all ownership and 
* intellectual property rights in the code accompanying this message and in all 
* derivatives hereto.  You may use this code, and any derivatives created by 
* any person or entity by or on your behalf, exclusively with Microchip's
* proprietary products.  Your acceptance and/or use of this code constitutes 
* agreement to the terms and conditions of this notice.
*
* CODE ACCOMPANYING THIS MESSAGE IS SUPPLIED BY MICROCHIP "AS IS".  NO 
* WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED 
* TO, IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A 
* PARTICULAR PURPOSE APPLY TO THIS CODE, ITS INTERACTION WITH MICROCHIP'S 
* PRODUCTS, COMBINATION WITH ANY OTHER PRODUCTS, OR USE IN ANY APPLICATION. 
*
* YOU ACKNOWLEDGE AND AGREE THAT, IN NO EVENT, SHALL MICROCHIP BE LIABLE, WHETHER 
* IN CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE OR BREACH OF STATUTORY DUTY), 
* STRICT LIABILITY, INDEMNITY, CONTRIBUTION, OR OTHERWISE, FOR ANY INDIRECT, SPECIAL, 
* PUNITIVE, EXEMPLARY, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, FOR COST OR EXPENSE OF 
* ANY KIND WHATSOEVER RELATED TO THE CODE, HOWSOEVER CAUSED, EVEN IF MICROCHIP HAS BEEN 
* ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE.  TO THE FULLEST EXTENT 
* ALLOWABLE BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO 
* THIS CODE, SHALL NOT EXCEED THE PRICE YOU PAID DIRECTLY TO MICROCHIP SPECIFICALLY TO 
* HAVE THIS CODE DEVELOPED.
*
* You agree that you are solely responsible for testing the code and 
* determining its suitability.  Microchip has no obligation to modify, test, 
* certify, or support the code.
************************************************************************/
//#define DEBUG_ENABLED

#include "Timer.h"
#include "uart.h"

BOOL timeout1 = FALSE; /* Timeout flag for Timer 1*/
BOOL timeout2 = FALSE; /* Timeout flag for Timer 2*/
BOOL timeout4 = FALSE; /* Timeout flag for Timer 4*/


static UINT32 msecCounter1;
static UINT32 msecCounter2;
static UINT32 msecCounter4;
static UINT32 profileCounter;

/*
********************************************************************************
* Function name 	: init_timer
* Input Parameters	: Timer Number
* Return Type		: None
* Functionality		: Initializes the timer module timer_num
********************************************************************************
*/
void init_timer(BYTE timer_num)
{
    if ( timer_num == TIMER1 )
    {
	/* This function will intialize the Timer 1
	 * for basic timer operation. It will enable
	 * timer interrupt. The one second flag is
	 * initialized and the millisecond counter is 
	 * initialized. */
        T1CON         = 0x0;			/* Basic Timer Operation		*/
	PR1           = TIMER1_PERIOD;	        /* Timer period in TimerFunctions.h 	*/

	IFS0CLR      |= 0x10;			/* Clear interrupt flag and enable	*/
	IEC0SET      |= 0x10;			/* timer 1 interrupt. 			*/
	IPC1bits.T1IP = 4;		/* Timer 1 priority is 4		*/
      
        
    }
    if ( timer_num == TIMER2 )
    {
	/* This function will intialize the Timer 2
	 * for basic timer operation. It will enable
	 * timer interrupt. The one second flag is
	 * initialized and the millisecond counter is
	 * initialized. */
        T2CON         = 0x0;			/* Basic Timer Operation		*/
        PR2           = TIMER2_PERIOD;	        /* Timer period in TimerFunctions.h 	*/

	IFS0CLR      |= 0x100;			/* Clear interrupt flag and enable	*/
	IEC0SET      |= 0x100;			/* timer 2 interrupt. 			*/
	IPC2bits.T2IP = 4;		/* Timer 2 priority is 4		*/
    }
    if ( timer_num == TIMER4 )
    {
	/* This function will intialize the Timer 4
	 * for basic timer operation. It will enable
	 * timer interrupt. The one second flag is
	 * initialized and the millisecond counter is
	 * initialized. */
        T4CON         = 0x0;			/* Basic Timer Operation		*/
        PR4           = TIMER4_PERIOD;	        /* Timer period in TimerFunctions.h 	*/

	IFS0CLR      |= 0x10000;			/* Clear interrupt flag and enable	*/
	IEC0SET      |= 0x10000;			/* timer 4 interrupt. 			*/
	IPC4bits.T4IP = 4;		/* Timer 1 priority is 4		*/
    }
}
/*
********************************************************************************
* Function name 	: start_timer
* Input Parameters	: timeout value in millisecond
* Return Type		: None
* Functionality		: starts the timer 1 with timeout value
********************************************************************************
*/
void start_timer(UINT32 timems)
{
    MSEC1        = timems*10;
    timeout1     = FALSE;
    msecCounter1 = 0;		/* and the millisecond counter.		*/
    T1CONSET     = 0x8000;		/* Start the timer.*/
}
/*
********************************************************************************
* Function name 	: stop_timer
* Input Parameters	: None 
* Return Type		: None
* Functionality		: stops the timer module 
********************************************************************************
*/
void stop_timer()
{
  T1CONCLR = 0x8000;		/* Stop the timer.*/
}
/*
******************************************************************************
* Function name 	: delayMs
* Input Parameters	: Int values
* Return Type		: None
* Functionality		: Enables the timer 2 for delay and waits till timems
*                         in a while loop
******************************************************************************
*/
void delayMs(UINT32 timems)
{
    	/* This function will intialize the Timer 2
	 * for basic timer operation. It will enable
	 * timer interrupt. The one second flag is
	 * initialized and the millisecond counter is
	 * initialized. */
        //T1CON = 0x00000030;
        MSEC2 = timems*10;

        timeout2 = FALSE;	 /* Intialize the one second flag	*/
	msecCounter2 = 0;	 /* and the millisecond counter.	*/

        T2CONSET = 0x8000;	 /* Start the timer.			*/

        while((timeout2 == FALSE));

        T2CONCLR = 0x8000;
}

void led_event_start(UINT32 timems)
{
        MSEC4        = timems*10;
        timeout4     = FALSE;
        msecCounter4 = 0;		/* and the millisecond counter.		*/
        T4CONSET     = 0x8000;          /* Start the timer.*/
}

void led_event_stop()
{
        T4CONCLR = 0x8000;		/* Stop the timer.*/
}
	


void __attribute__((vector(_TIMER_1_VECTOR), interrupt(ipl4), nomips16)) Timer1InterruptHandler(void)
{
	/* This is the Timer 1 ISR */
      	IFS0CLR |= 0x10; 	        /* Clear the Interrupt Flag	*/
	msecCounter1 ++;	        /* Increment millisecond counter.	*/

        if(msecCounter1 == MSEC1)
	{
	  /* This means that one second
	   * has expired since the last time
	   * msecCounter was 0. */

	   timeout1 = TRUE;	          /* Indicate that one second is up	*/
	   msecCounter1 = 0;	          /* Reset the millisecond counter.	*/
           T1CONCLR = 0x8000;
        }
}
void __attribute__((vector(_TIMER_2_VECTOR), interrupt(ipl4), nomips16)) Timer2InterruptHandler(void)
{
	/* This is the Timer 1 ISR */
        IFS0CLR |= 0x100; 	        /* Clear the Interrupt Flag	*/
	msecCounter2 ++;	        /* Increment millisecond counter.	*/
	if(msecCounter2 == MSEC2)
	{
	  /* This means that one second
	   * has expired since the last time
	   * msecCounter was 0. */
	   timeout2 = TRUE;	          /* Indicate that one second is up	*/
	   msecCounter2 = 0;	          /* Reset the millisecond counter.	*/
            //UART_Print("Inside ISR2\r\n");
        }
}
void __attribute__((vector(_TIMER_3_VECTOR), interrupt(ipl4), nomips16)) Timer3InterruptHandler(void)
{
	/* This is the Timer 2 ISR */
       	IFS0CLR |= 0x1000; 	            /* Clear the Interrupt Flag	*/
	profileCounter++;		    /* Increment microsecond counter.	*/
}
void __attribute__((vector(_TIMER_4_VECTOR), interrupt(ipl4), nomips16)) Timer4InterruptHandler(void)
{
	/* This is the Timer 1 ISR */
        IFS0CLR |= 0x10000; 	        /* Clear the Interrupt Flag	*/
	msecCounter4 ++;	        /* Increment millisecond counter.	*/
	if(msecCounter4 == MSEC4)
	{
	  /* This means that one second
	   * has expired since the last time
	   * msecCounter was 0. */
	   timeout4 = TRUE;	          /* Indicate that one second is up	*/
	   msecCounter4 = 0;	          /* Reset the millisecond counter.	*/
            //UART_Print("Inside ISR2\r\n");
           T4CONCLR = 0x8000;		/* Stop the timer.*/
        }
}
/*
******************************************************************************
* Function name 	: TimerTest
* Input Parameters	: None
* Return Type		: none
* Functionality		: TIMER UNIT TEST FUNCTIONS
******************************************************************************
*/
void TimerTest(void)
{
    start_timer(3000);
    UART_Print("Initialized UART TX1\r\n");
    delayMs(1000);
    UART_Print("Initialized UART TX2\r\n");
}
#ifdef PROFILE
/*
******************************************************************************
* Function name 	: init_profiling
* Input Parameters	: None
* Return Type		: none
* Functionality		: Initializes the timer profiling using TIMER 2
******************************************************************************
*/
inline void init_profiling()
{
    T3CON = 0x0;		 /* Basic Timer Operation		*/
    PR3 = PROFILE_PERIOD;	 /* Timer period in TimerFunctions.h 	*/
    IFS0CLR |= 0x1000;	         /* Clear interrupt flag and enable	*/
    IEC0SET |= 0x1000;	         /* timer 2 interrupt. 			*/
    IPC3bits.T3IP = 4;	         /* Timer 2 priority is 4		*/
}
/*
******************************************************************************
* Function name 	: start_profiling
* Input Parameters	: None
* Return Type		: none
* Functionality		: starts the profiling using TIMER 2
******************************************************************************
*/
inline void start_profiling()
{
    profileCounter = 0;
    T3CONSET = 0x8000;		/* Start the timer.*/
}
/*
******************************************************************************
* Function name 	: stop_profiling
* Input Parameters	: None
* Return Type		: none
* Functionality		: stops the profiling using TIMER 2
******************************************************************************
*/
inline void stop_profiling()
{
    T3CONCLR = 0x8000;
    printString("the time %d in microsecond\n\r",(profileCounter));
      
}
#endif

